package com.xzq.client;

import com.xzq.codec.MessageCodec;
import com.xzq.codec.ProcotolFrameDecoder;
import com.xzq.server.ServerMessageHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.Data;

import java.net.InetSocketAddress;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/22 21:39
 * @Version 1.0.0
 **/
@Data
public class NettyClient {
    private NioEventLoopGroup worker = new NioEventLoopGroup();
    private Channel channel;

    public ChannelFuture connect(InetSocketAddress address) {
        ChannelFuture f = null;
        try {
            Bootstrap client = new Bootstrap();
            client.group(worker)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.AUTO_READ, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //半包粘包解码器
                            socketChannel.pipeline().addLast(new ProcotolFrameDecoder());
                            //消息编解码器
                            socketChannel.pipeline().addLast(new MessageCodec());
                            //消息处理器
                            socketChannel.pipeline().addLast(new NettyMessageHandler());
                        }
                    });
            f = client.connect(address).sync();
            channel = f.channel();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }
}
